//
//  WHYBottomTabBar.m
//  News163
//
//  Created by 王洪运 on 15/12/29.
//  Copyright © 2015年 王洪运. All rights reserved.
//

#import "WHYBottomTabBar.h"
#import "WHYBottomTabBarButton.h"

@interface WHYBottomTabBar ()

@property (weak, nonatomic) UIButton *selectedButton;

@end

@implementation WHYBottomTabBar

#pragma mark - 加载子控件
-(void)layoutSubviews {
    [super layoutSubviews];
    
    NSUInteger count = self.subviews.count;
    
    CGFloat btnW = self.width / count;
    CGFloat btnH = self.height;
    CGFloat btnY = 0;
    
    for (int i = 0; i < count; i++) {
        CGFloat btnX = btnW * i;
        
        UIButton *btn = self.subviews[i];
        btn.frame = CGRectMake(btnX, btnY, btnW, btnH);
        
        btn.tag = i;
        
        if (i == 0) {
            btn.selected = YES;
            self.selectedButton = btn;
        }
    }
}

#pragma mark - 添加BottomTabBarButton
-(void)addBottomTabBarButtonWithNormalImageName:(NSString *)normal selectedImageName:(NSString *)selected {
    
    WHYBottomTabBarButton *btn = [[WHYBottomTabBarButton alloc] init];
    
    UIImage *normalImage = [UIImage imageNamed:normal];
    UIImage *selectedImage = [UIImage imageNamed:selected];
    
    [btn setImage:normalImage forState:UIControlStateNormal];
    [btn setImage:selectedImage forState:UIControlStateSelected];
    
    btn.contentMode = UIViewContentModeScaleToFill;

    [self addSubview:btn];
    
    [btn addTarget:self action:@selector(didClickTabBatButton:) forControlEvents:UIControlEventTouchUpInside];
}

//按钮点击事件
-(void)didClickTabBatButton:(UIButton *)button {
    
    self.selectedButton.selected = NO;
    button.selected = YES;
    self.selectedButton = button;
    
    NSInteger index = button.tag;
    
    if ([self.delegate respondsToSelector:@selector(bottomTabBar: didClickTabBarButtonWithIndex:)]) {
        [self.delegate bottomTabBar:self didClickTabBarButtonWithIndex:index];
    }
    
}



@end
